<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Models\NewBookRecommend;
use App\Models\RecommendBook;
use App\Models\RecommendUser;
use App\Models\ShopBook;
use Illuminate\Support\Facades\DB;

/**
 * 图书荐购
 */
class RecommendBookController extends Controller
{
    public $model = null;
    public $recommendUserModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new RecommendBook();
        $this->recommendUserModel = new RecommendUser();
    }


    /**
     * 新书荐购
     * @param token  用户token
     * @param isbn   isbn号
     * @param book_name  书名
     * @param author  作者
     * @param press  出版社
     * @param pre_time  出版时间
     * @param price  价格
     * @param intro  备注
     */
    public function newBookRecom()
    {

        if (empty($this->request->isbn) && (empty($this->request->book_name || $this->request->author))) {
            return $this->returnApi(201, '参数错误');
        }
        if (!empty($this->request->isbn) && !check_isbn($this->request->isbn)) {
            return $this->returnApi(201, 'isbn号规则不正确');
        }
        $isbn = $this->request->isbn;
        $isbn = str_replace('-', '', $isbn);

        //增加行为分析
        $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(14);

        //判断图书馆是否有此书
        if (config('other.is_validate_lib_api')) {
            $libApi = $this->getLibApiObj();
            if (!empty($isbn)) {
                $lib_exixts = $libApi->getBookInfo($isbn, "id", "desc", 1, 1, "isbn");
            } else {
                $lib_exixts = $libApi->getBookInfo($this->request->book_name, "id", "desc", 1, 1, "title");
            }

            if ($lib_exixts['code'] == 200) {
                return $this->returnApi(201, '此书图书馆已存在，请至图书馆进行借阅');
            }
        }

        //判断此书是否已经
        if (!empty($isbn)) {
            $res = $this->model->where('isbn', $isbn)->first();
        } else {
            $res = $this->model->where('book_name', $this->request->book_name)->where('author', $this->request->author)->first();
        }
        if (isset($res->status) && $res->status == 4) {
            return $this->returnApi(201, '此书图书馆已存在，请至图书馆进行借阅');
        }

        if ($res) {
            //判断此用户是否荐购过此书
            $is_exists = $this->recommendUserModel->where('user_id', $this->request->user_info['id'])->where('recom_id', $res->id)->first();
            if ($is_exists) {
                return $this->returnApi(201, '您已荐购过此书，请勿重复荐购');
            }
        }

        DB::beginTransaction();
        try {
            //写入图书荐购表
            if (empty($res)) {
                $this->request->merge(['number' => 1]); //追加到request里面
                $data['book_name'] = $this->request->book_name;
                $data['author'] = $this->request->author;
                $data['isbn'] = $isbn;
                $this->model->add($data);
                $recom_id = $this->model->id;
            } else {
                //增加荐购次数
                $res->number = ++$res->number;
                $res->save();
                $recom_id = $res->id;
            }
            $this->recommendUserModel->user_id = $this->request->user_info['id'];
            $this->recommendUserModel->recom_id = $recom_id;
            $this->recommendUserModel->book_name = $this->request->book_name;
            $this->recommendUserModel->author = $this->request->author;
            $this->recommendUserModel->isbn = $isbn;
            $this->recommendUserModel->press = $this->request->press;
            $this->recommendUserModel->pre_time = $this->request->pre_time;
            $this->recommendUserModel->price = $this->request->price;
            $this->recommendUserModel->img = $this->request->img;
            $this->recommendUserModel->intro = $this->request->intro;
            $this->recommendUserModel->save();

            DB::commit();
            return $this->returnApi(200, '荐购成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 扫码关联其他书籍信息
     * @param isbn
     */
    public function getBookInfo()
    {
        $isbn = $this->request->isbn;
        $isbn = str_replace('-', '', $isbn);
        if (empty($this->request->isbn) || !check_isbn($this->request->isbn)) {
            return $this->returnApi(201, 'isbn号规则不正确');
        }
        //判断图书馆是否有此书
        if (config('other.is_validate_lib_api')) {
            $libApi = $this->getLibApiObj();
            $book_info = $libApi->getBookInfo($isbn, "id", "desc", 1, 1, "isbn");
            if ($book_info['code'] == 200 && !empty($book_info['content']['data'])) {
                return $this->returnApi(200, '获取成功', true, $book_info['content']['data']);
            }
        }
        //从书店数据获取
        $book_info = NewBookRecommend::select('id', 'book_name', 'author', 'isbn', 'press', 'pre_time', 'price', 'img')->where('isbn', $isbn)->first();
        if ($book_info) {
            return $this->returnApi(200, '获取成功', true, $book_info);
        }
        return $this->returnApi(203, '暂无数据');
    }



    /**
     * 我的荐购历史
     * @param token
     * @param page  页数 默认为 1
     * @param limit  限制条数  默认 10 条
     */
    public function myRecomList()
    {
        $limit = $this->request->input('limit', 10);
        $user_id = $this->request->user_info['id'];

        $res = $this->model->from($this->model->getTable() . ' as b')
            ->select('b.id', 'u.book_name', 'u.author', 'u.isbn', 'u.press', 'u.pre_time', 'u.price', 'u.intro', 'b.number', 'b.status', 'b.reason', 'u.create_time')
            ->join('recommend_user as u', 'u.recom_id', '=', 'b.id')
            ->where('u.user_id', $user_id)
            ->orderByDesc('create_time')
            ->paginate($limit)
            ->toArray();

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "获取成功", true, $res);
    }
}
